package com.tutu.service.impl;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.tutu.controller.CommonsController;
import com.tutu.core.Constant;
import com.tutu.core.api.*;
import com.tutu.entity.vo.BaseCodeVo;
import com.tutu.service.CompanyService;
import com.tutu.service.DeviceService;
import com.tutu.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * companyServiceImpl
 * Created by 奕恒 on 2022/10/20 21:50.
 */
@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    DeviceService deviceService;

    @Override
    public Map<String, Object> pageByParams(String keyWord, Integer pageNum, Integer pageSize) {
        return HttpRequestUtil.getOnlyData(CompanyApiUrls.base_prefix + CompanyApiUrls.page, "keyWord=" + UnicodeUtil.unicodeEncode(keyWord) + "&pageNum=" + pageNum + "&pageSize=" + pageSize);
    }

    @Override
    public Map<String, Object> pageByParams(Integer companyId, String keyWord, Integer type, Integer pageNum, Integer pageSize) {
        return HttpRequestUtil.getOnlyData(UserApiUrls.base_prefix + UserApiUrls.pageWithCompany, "companyId=" + companyId + "&keyWord=" + UnicodeUtil.unicodeEncode(keyWord) + "&type=" + type + "&pageNum=" + pageNum + "&pageSize=" + pageSize);
    }

    @Override
    public Map<String, Object> getInfoById(Integer id) {
        for (Map<String, Object> map : CommonsController.baseCompanyList)
            if (map.get("id").equals(id)) return map;

        return new HashMap<>();
    }

    @Override
    public List<BaseCodeVo> findUserListByCompanyId(Integer companyId) {
        return BaseUtil.getListResult(DeviceApiUrls.base_prefix + DeviceApiUrls.findUserListByCompanyId, "companyId=" + companyId);
    }

    @Override
    public Map<String, Object> updateCompanyUser(HttpServletRequest request, Integer companyId, Integer selectCompanyId, String userIds) {
        LogInfoServiceImpl.saveLogInfo(request, "更新公司和用户的关联关系，公司ID：" + companyId + "，选择公司ID：" + selectCompanyId + "，用户IDS：" + userIds);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(DeviceUserApiUrls.base_prefix + DeviceUserApiUrls.updateCompanyUser, "companyId=" + companyId + "&userIds=" + userIds + "&status=" + selectCompanyId);

        loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> saveInfo(HttpServletRequest request, Integer id, String name, String endTime) {
        LogInfoServiceImpl.saveLogInfo(request, "编辑公司信息，ID：" + id + "，名称：" + name + "，过期时间：" + endTime);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(CompanyApiUrls.base_prefix + CompanyApiUrls.update, "id=" + id + "&name=" + UnicodeUtil.unicodeEncode(name) + (StringUtils.isNotBlank(endTime) ? "&endTime=" + DateUtils.stringToLongWithFormat(endTime, Constant.TIME_FORMAT_DATE) : ""));

        loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> deleteById(HttpServletRequest request, Integer id) {
        LogInfoServiceImpl.saveLogInfo(request, "删除公司信息，ID：" + id);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(CompanyApiUrls.base_prefix + CompanyApiUrls.delete, "id=" + id);

        loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> batchDel(HttpServletRequest request, String ids) {
        LogInfoServiceImpl.saveLogInfo(request, "批量删除公司信息，IDS：" + ids);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(CompanyApiUrls.base_prefix + CompanyApiUrls.batchDel, "ids=" + ids);

        loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> setContact(HttpServletRequest request, Integer companyId, Integer userId, Integer type) {
        LogInfoServiceImpl.saveLogInfo(request, "编辑公司联系人，公司ID：" + companyId + "，用户ID：" + userId + "，操作类型：" + type);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(CompanyUserApiUrls.base_prefix + CompanyUserApiUrls.setContact, "companyId=" + companyId + "&userId=" + userId + "&type=" + type);

        loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> cleanContact(HttpServletRequest request, Integer companyId) {
        LogInfoServiceImpl.saveLogInfo(request, "清理公司所有联系人，公司ID：" + companyId);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(CompanyUserApiUrls.base_prefix + CompanyUserApiUrls.cleanContact, "companyId=" + companyId);

        loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> syncData(HttpServletRequest request) {
        LogInfoServiceImpl.saveLogInfo(request, "同步公司信息");

        Map<String, Object> map;

        if (CommonsController.needSync("company")) {
            map = HttpRequestUtil.getSyncData(4);
        } else {
            map = BaseUtil.defaultErrorInfo(null);
        }

        loadCacheData();

        return map;
    }

    @Override
    public Map<String, Object> mergeInfo(HttpServletRequest request, Integer mainCompanyId, Integer otherCompanyId) {
        LogInfoServiceImpl.saveLogInfo(request, "合并公司信息，主公司ID：" + mainCompanyId + "，被合并公司ID：" + otherCompanyId);

        Map<String, Object> map = HttpRequestUtil.getCompleteData(CompanyApiUrls.base_prefix + CompanyApiUrls.mergeCompanyInfo, "mainCompanyId=" + mainCompanyId + "&otherCompanyId=" + otherCompanyId);

        loadCacheData();

        deviceService.loadCacheData(request);

        return map;
    }

    @Override
    public void createQRCode(HttpServletResponse response, Integer companyId) {
        try {
            // 2.生成二维码
            BitMatrix bitMatrix = QRCodeUtil.createCode(companyId + "");

            // 3.以流的形式输出到前端
            MatrixToImageWriter.writeToStream(bitMatrix, "jpg", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void loadCacheData() {
        CommonsController.baseCompanyList.clear();

        for (Object o : HttpRequestUtil.getListData(CompanyApiUrls.base_prefix + CompanyApiUrls.list, ""))
            CommonsController.baseCompanyList.add(JsonUtil.json2Map(o));

        if (CommonsController.baseCompanyList.size() == 0) {
            try {
                log.info("公司信息请求失败，3秒后自动重试...");

                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            loadCacheData();
        }

        log.info("共计加载" + CommonsController.baseCompanyList.size() + "条公司信息...");
    }
}
